package com.weilan.blog.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.weilan.blog.admin.service.BlogTagService;
import com.weilan.blog.admin.mapper.BlogTagMapper;
import com.weilan.blog.admin.service.BlogService;
import com.weilan.blog.admin.vo.BlogTagVO;
import com.weilan.blog.base.enums.EPublish;
import com.weilan.blog.base.enums.EStatus;
import com.weilan.blog.base.serviceImpl.SuperServiceImpl;
import com.weilan.blog.common.global.MessageConf;
import com.weilan.blog.common.global.SQLConf;
import com.weilan.blog.common.global.SysConf;
import com.weilan.blog.admin.entity.Blog;
import com.weilan.blog.admin.entity.BlogTag;
import com.weilan.blog.utils.ResultUtil;
import com.weilan.blog.utils.StringUtils;
import com.weilan.blog.utils.UpdateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @description:
 * @author: 孙 峰
 * @time: 2020/9/27 10:36
 */
@Service
public class BlogTagServiceImpl extends SuperServiceImpl<BlogTagMapper, BlogTag> implements BlogTagService {


    @Autowired
    private BlogService blogService;

    @Autowired
    private BlogTagService blogTagService;


    @Override
    public IPage<BlogTag> getPageList(BlogTagVO blogTagVO) {
        QueryWrapper<BlogTag> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(blogTagVO.getKeyword()) && !StringUtils.isEmpty(blogTagVO.getKeyword())) {
            queryWrapper.like(SQLConf.CONTENT, blogTagVO.getKeyword().trim());
        }


        Page<BlogTag> page = new Page<>();
        page.setCurrent(blogTagVO.getCurrentPage());
        page.setSize(blogTagVO.getPageSize());
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        queryWrapper.orderByDesc(SQLConf.SORT);
        IPage<BlogTag> pageList = this.page(page, queryWrapper);
        return pageList;
    }

    @Override
    public List<BlogTag> getList() {
        return null;
    }

    @Override
    public String addTag(BlogTagVO tagVO) {
        QueryWrapper<BlogTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.CONTENT, tagVO.getContent());
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        BlogTag tempTag = this.getOne(queryWrapper);
        if (tempTag != null) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.ENTITY_EXIST);
        }
        BlogTag blogTag = new BlogTag();
        UpdateUtil.copyNullProperties(tagVO, blogTag);
        blogTag.setClickCount(0);
        blogTag.setStatus(EStatus.ENABLE);
        this.save(blogTag);
        return ResultUtil.result(SysConf.SUCCESS, MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String editTag(BlogTagVO tagVO) {
        return null;
    }

    @Override
    public String deleteBatchBlogTag(List<BlogTagVO> tagVOList) {
        if (tagVOList.size() <= 0) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.PARAM_INCORRECT);
        }
        List<String> uids = new ArrayList<>();
        tagVOList.forEach(item -> {
            uids.add(item.getUid());
        });

        // 判断要删除的分类，是否有博客
        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        blogQueryWrapper.in(SQLConf.TAG_UID, uids);
        Integer blogCount = blogService.count(blogQueryWrapper);
        if (blogCount > 0) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.BLOG_UNDER_THIS_TAG);
        }

        Collection<BlogTag> tagList = listByIds(uids);

        tagList.forEach(item -> {
            item.setUpdateTime(LocalDateTime.now());
            item.setStatus(EStatus.DISABLED);
        });

        Boolean save = updateBatchById(tagList);
        // 删除和标签相关的博客缓存
        blogService.deleteRedisByBlogTag();
        if (save) {
            return ResultUtil.result(SysConf.SUCCESS, MessageConf.DELETE_SUCCESS);
        } else {
            return ResultUtil.result(SysConf.ERROR, MessageConf.DELETE_FAIL);
        }
    }

    @Override
    public String deleteBatchBlogTag(String[] ids) {
        return null;
    }

    @Override
    public String stickBlogTag(BlogTagVO tagVO) {
        BlogTag tag = blogTagService.getById(tagVO.getUid());

        //查找出最大的那一个
        QueryWrapper<BlogTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(SQLConf.SORT);
        Page<BlogTag> page = new Page<>();
        page.setCurrent(0);
        page.setSize(1);
        IPage<BlogTag> pageList = blogTagService.page(page, queryWrapper);
        List<BlogTag> list = pageList.getRecords();
        BlogTag maxTag = list.get(0);

        if (StringUtils.isEmpty(maxTag.getUid())) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.PARAM_INCORRECT);
        }
        if (maxTag.getUid().equals(tag.getUid())) {
            return ResultUtil.result(SysConf.ERROR, MessageConf.THIS_TAG_IS_TOP);
        }

        Integer sortCount = maxTag.getSort() + 1;

        tag.setSort(sortCount);
        tag.setUpdateTime(LocalDateTime.now());
        tag.updateById();

        return ResultUtil.result(SysConf.SUCCESS, MessageConf.OPERATION_SUCCESS);
    }

    @Override
    @Transactional
    public String tagSortByClickCount() {
        QueryWrapper<BlogTag> queryWrapper = new QueryWrapper();
        queryWrapper.eq(SQLConf.STATUS,EStatus.ENABLE);
        //按照点击量从高到低排序
        queryWrapper.orderByDesc(SQLConf.CLICK_COUNT);
        List<BlogTag> blogTags = blogTagService.list(queryWrapper);
        blogTags.forEach(blogTag -> {
            blogTag.setSort(blogTag.getClickCount());
            blogTag.setUpdateTime(LocalDateTime.now());
        });
        blogTagService.updateBatchById(blogTags);

        return ResultUtil.result(SysConf.SUCCESS,MessageConf.OPERATION_SUCCESS);
    }

    @Override
    public String tagSortByCite() {
        // 定义Map   key：tagUid,  value: 引用量
        Map<String, Integer> map = new HashMap<>();

        QueryWrapper<BlogTag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        List<BlogTag> tagList = blogTagService.list(tagQueryWrapper);
        // 初始化引用排序
        tagList.forEach(blogTag -> {
            map.put(blogTag.getUid(),0);
        });


        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        queryWrapper.eq(SQLConf.IS_PUBLISH, EPublish.PUBLISH);


        // 过滤content字段
        queryWrapper.select(Blog.class, i -> !i.getProperty().equals(SQLConf.CONTENT));
        List<Blog> blogList = blogService.list(queryWrapper);
        blogList.forEach(item -> {
            String tagUids = item.getTagUid();
            List<String> tagUidList = StringUtils.changeStringToString(tagUids, SysConf.FILE_SEGMENTATION);
            for (String tagUid : tagUidList) {
                if (map.get(tagUid) != null) {
                    Integer count = map.get(tagUid) + 1;
                    map.put(tagUid, count);
                } else {
                    map.put(tagUid, 0);
                }
            }
        });
        tagList.forEach(item -> {
            item.setSort(map.get(item.getUid()));
            item.setUpdateTime(LocalDateTime.now());
        });
        blogTagService.updateBatchById(tagList);
        return ResultUtil.result(SysConf.SUCCESS, MessageConf.OPERATION_SUCCESS);
    }

    /**
     * 根据点击量获取热门标签
     * @param hotTagCount
     * @return
     */
    @Override
    public IPage<BlogTag> getHotTag(Integer hotTagCount) {
        QueryWrapper<BlogTag> queryWrapper = new QueryWrapper<>();
        Page<BlogTag> page = new Page<>();
        page.setCurrent(1);
        page.setSize(hotTagCount);
        queryWrapper.eq(SQLConf.STATUS, EStatus.ENABLE);
        queryWrapper.orderByDesc(SQLConf.SORT);
        queryWrapper.orderByDesc(SQLConf.CLICK_COUNT);
        IPage<BlogTag> pageList = blogTagService.page(page, queryWrapper);
        return pageList;
    }

    @Override
    public BlogTag getTopTag() {
        QueryWrapper<BlogTag> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq(SQLConf.STATUS,EStatus.ENABLE);
        tagQueryWrapper.last(SysConf.LIMIT_ONE);
        tagQueryWrapper.orderByDesc(SQLConf.SORT);
        BlogTag blogTag = blogTagService.getOne(tagQueryWrapper);
        return blogTag;
    }
}
